package com.pactera.integral.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import com.pactera.integral.dao.AuthorityDao;
import com.pactera.integral.entity.Authority;


public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource,InitializingBean {
    @Autowired
    private AuthorityDao roleDao;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private List<Authority> roleList = new ArrayList<Authority>();


    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        // String httpMethod = fi.getRequest().getMethod();
        for (Authority role:roleList) {
            if (antPathMatcher.match(role.getPattern(), url)) {
                return SecurityConfig.createList(role.getName());
            }
        }
        return null;
        // return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

    /**
     * @throws Exception
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        roleList.addAll(roleDao.findAll());
    }
}
